package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealdishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /***
     * 新增菜品和对应口味
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveWithFlavors(DishDTO dishDTO) {
        //上传菜品信息
        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);

        //上传菜品味道
        Long dishid = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();//获取味道列表

        if(flavors !=null && flavors.size()>0){
            flavors.forEach(flavor->{
                flavor.setDishId(dishid);
            });

            dishFlavorMapper.insert(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void delectBatch(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for(Long id:ids){
            Dish dish=dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除---是否被套餐关联了？？
        //setmeal_dish表中含有 setmeal_id 及 dish_id 字段 中间连接表
        List<Long> setmealIds = setmealdishMapper.getSetmealIdsByDishIds(ids);
        if(!setmealIds.isEmpty() && setmealIds != null){
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        for(Long id:ids){
            dishMapper.deleteById(id);//删除菜品除口味外相关数据
            dishFlavorMapper.deleteByDishId(id);//删除菜品关联的口味数据
        }
    }

    /**
     * 根据id查询菜品及味道并封装为DishVO类
     * @param id
     * @return
     */
    @Transactional
    @Override
    public DishVO getByIdWithFalvor(Long id) {
        //查询菜品数据及其味道
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> flavors=dishFlavorMapper.getByDishId(id);

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dish.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors !=null && !flavors.isEmpty()){
            //为每一条味道修改对应菜品id
            flavors.forEach(dishFlavor->{
                dishFlavor.setDishId(dish.getId());
            });
            //修改完毕后插入
            dishFlavorMapper.insert(flavors);
        }
    }

    /**
     * 菜品起售及停售
     * @param id
     */
    @Override
    public void startOrStop(Integer status,Long id) {
        //需要创建一个Diah类对象,使用Builder
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        //如果菜品停售，那么与菜品相关联的套餐也要停售
        List<Long> dishIds=new ArrayList<>();
        dishIds.add(id);

        if (status == StatusConstant.DISABLE) {
            List<Long> setmealIdsByDishIds = setmealdishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIdsByDishIds != null && !setmealIdsByDishIds.isEmpty()) {
                for (Long setmealId : setmealIdsByDishIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .status(StatusConstant.DISABLE)
                            .id(setmealId)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品，用于下拉列表
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        //建立查询条件
        Dish dish = Dish.builder()
                .status(StatusConstant.ENABLE)
                .categoryId(categoryId)
                .build();

        List<Dish> dishes=dishMapper.getBycategoryId(dish);
        return dishes;
    }

    /**
     * 条件查询在售菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listByFalvor(Dish dish) {
        List<Dish> dishList = dishMapper.getBycategoryId(dish);

        List<DishVO> dishVOList= new ArrayList<>();

        for(Dish dish1:dishList){
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish1,dishVO);

            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish1.getId());
            dishVO.setFlavors(flavors);

            dishVOList.add(dishVO);
        }
        return  dishVOList;
    }


}
